package com.nowcoder.community.controller;

import com.alibaba.fastjson2.JSONObject;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

/**
 * @author 韩
 * @version 1.0
 */
@Controller
public class MessageController implements CommunityConstant {

    @Autowired
    private MessageService messageService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @RequestMapping(path = "/letter/list", method = RequestMethod.GET)
    public String getConversationsPage(Model model, Page page) {
        //获取当前用户
        User user = hostHolder.getUser();
        //设置分页信息
        page.setPath("/letter/list");
        page.setRows(messageService.finConversationsCount(user.getId()));
        page.setLimit(5);

        //获取当前用户的会话列表
        List<Message> conversationList = messageService.findConversations(user.getId(), page.getOffset(), page.getLimit());
        //存储页面相关的会话信息
        List<Map<String, Object>> conversations = new ArrayList<>();
        if (conversationList != null) {
            for (Message conversation : conversationList) {
                Map<String, Object> map = new HashMap<>();
                map.put("conversation", conversation);
                //未读的私信数量
                map.put("unreadCount", messageService.findLetterUnreadCount(user.getId(), conversation.getConversationId()));
                map.put("letterCount", messageService.findLettersCount(conversation.getConversationId()));
                //判断当前用户是发起人还是接收人，以此来获取会话对方的用户信息
                int targetId = user.getId() == conversation.getFromId() ? conversation.getToId() : conversation.getFromId();
                //存放当前用户会话对方的相关信息，用来展示会话列表的头像
                map.put("target", userService.findUserById(targetId));
                conversations.add(map);
            }
        }
        model.addAttribute("conversations", conversations);
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        //查询未读通知总数量
        int noticeUnreadCount = messageService.findNoticeUnreadCount(null, user.getId());
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);
        return "/site/letter";
    }

    @RequestMapping(path = "/letter/detail/{conversationId}", method = RequestMethod.GET)
    public String getLetterDetailPage(@PathVariable("conversationId") String conversationId, Model model, Page page) {
        //设置分页信息
        page.setLimit(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setRows(messageService.findLettersCount(conversationId));

        //获取私信列表
        List<Message> letterList = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());

        //获取未读私信的id，并更新这些私信的状态
        List<Integer> ids = getUnreadLetterIds(letterList);
        if (!ids.isEmpty()) {
            messageService.updateMessageStatus(ids);
        }

        List<Map<String, Object>> letters = new ArrayList<>();
        if (letterList != null) {
            for (Message letter : letterList) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", letter);
                //存储发送者用户二点信息
                map.put("fromUser", userService.findUserById(letter.getFromId()));
                letters.add(map);
            }
        }
        model.addAttribute("letters", letters);
        //获取发件人
        User target = getFromUserByConversationId(conversationId);
        model.addAttribute("target", target);
        return "/site/letter-detail";
    }

    //私信列表中获取未读私信的id号
    public List<Integer> getUnreadLetterIds(List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();
        if (letterList != null) {
            for (Message letter : letterList) {
                //若当前用户是接收者并且私信状态是未读时，才需要更新，此时加入集合
                if (hostHolder.getUser().getId().equals(letter.getToId()) && letter.getStatus() == 0) {
                    ids.add(letter.getId());
                    System.out.println(letter.getContent());
                }
            }
        }
        return ids;
    }

    //从conversationId中获取发件人
    public User getFromUserByConversationId(String conversationId) {
        String[] id = conversationId.split("_");
        int id1 = Integer.parseInt(id[0]);
        int id2 = Integer.parseInt(id[1]);
        if (hostHolder.getUser().getId() == id1) {
            return userService.findUserById(id2);
        } else {
            return userService.findUserById(id1);
        }
    }

    @RequestMapping(path = "/letter/send", method = RequestMethod.POST)
    @ResponseBody
    public String sendLetter(String toName, String content) {
        //查询收件人用户名是否正确，不正确返回错误提示信息
        User user = userService.findUserByUsername(toName);
        if (user == null) {
            return CommunityUtil.getJsonString(1, "该用户名不存在！");
        }
        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(user.getId());
        //设置会话id，id为发件人和接收人id用_连接，小的id在前面
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(content);
        message.setStatus(0);
        message.setCreateTime(new Date());
        messageService.addMessage(message);

        return CommunityUtil.getJsonString(0);
    }

    @RequestMapping(path = "/notice/list", method = RequestMethod.GET)
    public String getNoticePage(Model model) {
        User user = hostHolder.getUser();

        //查询评论通知
        Message message = messageService.findLatestNotice(TOPIC_COMMENT, user.getId());

        if (message != null) {
            Map<String, Object> commentVo = new HashMap<>();
            commentVo.put("message", message);
            //将消息的content转换成原数据对象
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            //将内容放存入用于回显页面
            commentVo.put("user", userService.findUserById((Integer) data.get("userId")));
            commentVo.put("entityType", data.get("entityType"));
            commentVo.put("entityId", data.get("entityId"));
            commentVo.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(TOPIC_COMMENT, user.getId());
            commentVo.put("count", count);
            int unreadCount = messageService.findNoticeUnreadCount(TOPIC_COMMENT, user.getId());
            commentVo.put("unreadCount", unreadCount);
            model.addAttribute("commentNotice", commentVo);
        }


        //查询点赞通知
        message = messageService.findLatestNotice(TOPIC_LIKE, user.getId());

        if (message != null) {
            Map<String, Object> likeVo = new HashMap<>();
            likeVo.put("message", message);
            //将消息的content转换成原数据对象
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            //将内容放存入用于回显页面
            likeVo.put("user", userService.findUserById((Integer) data.get("userId")));
            likeVo.put("entityType", data.get("entityType"));
            likeVo.put("entityId", data.get("entityId"));
            likeVo.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(TOPIC_LIKE, user.getId());
            likeVo.put("count", count);
            int unreadCount = messageService.findNoticeUnreadCount(TOPIC_LIKE, user.getId());
            likeVo.put("unreadCount", unreadCount);
            model.addAttribute("likeNotice", likeVo);
        }


        //查询点赞通知
        message = messageService.findLatestNotice(TOPIC_FOLLOW, user.getId());

        if (message != null) {
            Map<String, Object> followVo = new HashMap<>();
            followVo.put("message", message);
            //将消息的content转换成原数据对象
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            //将内容放存入用于回显页面
            followVo.put("user", userService.findUserById((Integer) data.get("userId")));
            followVo.put("entityType", data.get("entityType"));
            followVo.put("entityId", data.get("entityId"));
            followVo.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(TOPIC_FOLLOW, user.getId());
            followVo.put("count", count);
            int unreadCount = messageService.findNoticeUnreadCount(TOPIC_FOLLOW, user.getId());
            followVo.put("unreadCount", unreadCount);
            model.addAttribute("followNotice", followVo);
        }


        //查询未读消息总数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        //查询未读通知总数量
        int noticeUnreadCount = messageService.findNoticeUnreadCount(null, user.getId());
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);
        return "/site/notice";
    }

    @RequestMapping(path = "/notice/detail/{topic}", method = RequestMethod.GET)
    public String getNoticeDetail(@PathVariable("topic") String topic, Model model, Page page) {
        User user = hostHolder.getUser();

        //设置分页信息
        page.setLimit(5);
        page.setPath("/notice/detail/" + topic);
        page.setRows(messageService.findNoticeCount(topic, user.getId()));

        List<Message> noticeList = messageService.findNotices(topic, user.getId(), page.getOffset(), page.getLimit());
        List<Map<String, Object>> notices = new ArrayList<>();
        if (noticeList != null) {
            for (Message notice : noticeList) {
                Map<String, Object> map = new HashMap<>();
                //通知
                map.put("notice", notice);
                //内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("user", userService.findUserById((Integer) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));
                //通知作者
                map.put("fromUser", userService.findUserById(notice.getFromId()));

                notices.add(map);
            }
        }
        model.addAttribute("notices", notices);

        //获取未读的通知id列表
        List<Integer> ids = getUnreadLetterIds(noticeList);
        if (!ids.isEmpty()) {
            messageService.updateMessageStatus(ids);
        }
        return "/site/notice-detail";
    }
}